from django.shortcuts import render, HttpResponse, redirect
from web import models
from web.utils.pagination import Pagination

from web.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm


def pretty_list(request):
    """靓号列表"""
    # request.GET 可以获取页面URL上的所有参数

    data_dic = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dic["mobile__contains"] = search_data

    queryset = models.PrettyNum.objects.filter(**data_dic).order_by("-level")
    page_object = Pagination(request, queryset)

    context = {
        'queryset': page_object.page_queryset,  # 分完页的数据
        'search_data': search_data,
        'page_string': page_object.html()  # 页码
    }

    return render(request, 'pretty_list.html', context)


def pretty_add(request):
    """添加靓号"""
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {'form': form})
    # 将表单数据传进来
    form = PrettyModelForm(data=request.POST)
    # 数据校验,通过：数据保存到数据库；不通过：返回添加页面，重新执行添加操作
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_add.html', {'form': form})


def pretty_edit(request, nid):
    """编辑靓号"""
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {'form': form})
    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {'form': form})


def pretty_delete(request, nid):
    """删除靓号"""
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')
